# -*- coding:utf-8 -*-
import requests
import csv
import json
import time
from tomorrow import threads
'''
主要功能：
1、食物量词识别
2、
'''
class foodQuantifiers():


    def login_token(self):

        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15812305820",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url, data=login_data, headers=login_header)
        # # 获取登录的响应报文
        # print(r_login.text)
        # login_response = json.loads(r_login.text)
        # # 保存登录的token信息
        # access_token = login_response['access_token']
        token = r_login.json()['access_token']
        print(token)
        '''请求接口获取token值'''
        return token

    @threads(500)  # 我们开500个线程去搞定接口任务
    def food_quantifiers(self):

        # 初始化
        food_flag_init = 0
        food_error_init = 0
        food_fail_init = 0
        # 接口初始化时间
        start = time.time()


        # 读取csv文件
        with open('E:\\test\\HB\\food_quantifiers_init_not.csv', 'r') as csvFile:
            reader = csv.reader(csvFile)
            print(type(reader))
            next(reader)
            for row in reader:
                print(row)
                print(type(row))
                print(row[0])
                print(type(row[0]))

                # 食物量词识别接口的请求参数msg
                food_msg = {"msg": row[0]}
                print(food_msg)


                food_headers = {"Authorization": "Bearer " + self.login_token()}
                # 食物量词的url
                food_url = 'https://api.icarbonx.com/nlp/api/v1.0/nutrition_query'
                # 量词识别模型接口请求
                r_food = requests.post(url=food_url, data=food_msg, headers=food_headers)
                # 获取响应报文
                print(r_food.text)
                # 转换响应结果为dict格式
                food_response = json.loads(r_food.text)
                print(food_response)
                print(type(food_response))

                # 判断响应结果是否为空,不为空，则获取食物food_name、food_id、food_init、food_grams
                if food_response:
                    print(food_response[0])
                    food_flag_init = food_flag_init + 1
                    print("食物量词识别响应成功结果：%d" %food_flag_init)
                    food_response_all = food_response[0]
                    food_quantifiers_food_name = food_response_all['food_name']
                    # 获取food_id的值
                    food_quantifiers_food_id = food_response_all['food_id']
                    food_quantifiers_food_unit = food_response_all['food_unit']
                    food_quantifiers_food_grams = food_response_all['food_grams']
                    print("food的name：" + food_quantifiers_food_name)
                    print("食物id：%d" %food_quantifiers_food_id)
                    print("食物单位：" + food_quantifiers_food_unit)
                    print("食物重量：%d" %food_quantifiers_food_grams)

                    #int转换为str
                    food_quantifiers_food_id = str(food_quantifiers_food_id)
                    food_quantifiers_food_grams = str(food_quantifiers_food_grams)

                    food_quantifiers_data = ['msg','food_name', 'grams', 'unit','id']

                    with open('E:\\test\\HB\\food_quantifier_success.csv','a+',encoding='utf-8-sig') as ff:

                        food_quantifiers_data[0] = row[0]
                        food_quantifiers_data[1] = food_quantifiers_food_name
                        food_quantifiers_data[2] = food_quantifiers_food_grams
                        food_quantifiers_data[3] = food_quantifiers_food_unit
                        food_quantifiers_data[4] = food_quantifiers_food_id
                        ff.write(','.join(food_quantifiers_data))
                        ff.write('\n')
                        ff.close()
                # 响应结果为空，可能食物量词无法识别
                else:
                    food_quantifiers_error_data = ['msg']
                    with open('E:\\test\\HB\\food_quantifier_error.csv','a+',encoding='utf-8-sig') as fx:

                        food_quantifiers_error_data[0] = row[0]
                        fx.write(','.join(food_quantifiers_error_data))
                        fx.write('\n')
                        fx.close()


                    food_error_init = food_error_init + 1
                    print("食物量词识别响应为空结果：%d" %food_error_init)

        csvFile.close()

        # # 使用线程池（使用100个线程池）
        # with ThreadPoolExecutor(max_workers = 100) as executor:
        #     # 此处使用的map操作和原生的map函数功能一样
        #     for num，result in zip(NUMBERS,executor,map(food_quantifiers,NUMBERS)):
        #         print()


        # 计算花费的时间
        print('cost time:{}'.format(time.time()-start))
        print("---食物量词识别模型统计结果"+ time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+"------")
        print("食物量词识别响应成功结果：%d" % food_flag_init)
        print("食物量词识别响应为空结果：%d" % food_error_init)




if __name__ == '__main__':
    fd = foodQuantifiers()
    fd.food_quantifiers()